<template>
    <div class="message-container">
        <div v-for="(message, index) in messages" :key="index" class="message" :style="{ bottom: `${index * 30}px` }"
            @transitionend="handleTransitionEnd(index)">
            <transition name="fade">
                <div v-if="!message.fadeOut">{{ message.text }}</div>
            </transition>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, watchEffect } from 'vue';

// 初始化消息列表  
const messages = ref([]);

onMounted(() => {
    setInterval(() => {
        for (let i = 0 ; i < messages.value.length ; i++){
            handleTransitionEnd(i)
        }
    }, 1000)
})

// 接收消息的方法  
async function receiveMessage(text) {
    // 检查文本长度，并处理换行  
    const formattedText = text.length > 10 ? `${text.slice(0, 10)}...` : text;

    // 添加新消息到列表  
    const newMessage = { text: formattedText, fadeOut: false };
    messages.value.unshift(newMessage);

    // 最多显示五条消息  
    if (messages.value.length > 5) {
        messages.value.pop();
    }

    // 设置消息在5秒后消失  
    await setTimeout(() => {
        newMessage.fadeOut = true;
    }, 5000);

}

// 处理消息消失后的过渡结束事件  
function handleTransitionEnd(index) {
    if (messages.value[index].fadeOut) {
        messages.value.splice(index, 1);
    }
}

// 暴露给父组件的接收消息方法  
defineExpose({
    receiveMessage
});
</script>

<style scoped>
.message-container {
    position: fixed;
    bottom: 7rem;
    left: 2rem;
    width: 50%;
    height:auto;
    display: flex;
    flex-direction: column-reverse;
    align-items: flex-start;
    padding: 10px;
    box-sizing: border-box;
    pointer-events: none;
    /* 防止点击穿透 */
    z-index: 100000000;
}

.message {
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 5px 10px;
    border-radius: 5px;
    max-width: 80%;
    white-space: pre-wrap;
    /* 自动换行 */
    /* position: relative; */
    margin-bottom: 2px;
    pointer-events: auto;
    /* 允许点击事件 */
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to

/* .fade-leave-active below version 2.1.8 */
    {
    opacity: 0;
}
</style>